package com.dormitory.httpHelper;

import android.util.Log;

import com.dormitory.bean.DormitoryBean;
import com.dormitory.bean.FileBean;
import com.dormitory.staticVariable.StaticVariable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by JHF on 2017/10/20.
 */

public class HttpFile {
    public static void uploadFile(File file, String userName, int dormitoryId, boolean isSharing) throws Exception {
        final String BOUNDARY =  UUID.randomUUID().toString().replace("-", "");  //边界标识   随机生成
        final String PREFIX = "--" , LINE_END = "\r\n";

        URL url = new URL(StaticVariable.UPLOADFILE_SERVLET);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setReadTimeout(50000);
        conn.setConnectTimeout(50000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setChunkedStreamingMode(1024*1024);

        conn.setRequestProperty("Charset", "utf-8");  //设置编码
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + BOUNDARY);

        if(file != null) {
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();

            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            JSONObject json = new JSONObject();
            json.put("userName", userName);
            json.put("dormitoryId", dormitoryId);
            json.put("isSharing", isSharing);

            sb.append("Content-Disposition: form-data; name=\"data\"" + LINE_END);
            sb.append(LINE_END);
            sb.append(json.toString());
            sb.append(LINE_END);

            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"file\";filename=\"" + file.getName() + "\"" + LINE_END);
            sb.append("Content-Type: application/octet-stream" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024*1024];
            int len = 0;
            long fileLength = file.length();
            while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            conn.connect();
            //Log.e("tag", conn.getResponseCode()+"");
            if (conn.getResponseCode() == 200) {
                InputStream iis = conn.getInputStream();
                BufferedReader bf = new BufferedReader(new InputStreamReader(iis));
                StringBuffer data0 = new StringBuffer();
                String buffer;
                while(((buffer) = bf.readLine())!=null) {
                    data0.append(buffer);
                }
                if(!data0.toString().equals("true")) {
                    throw new Exception("上传失败");
                }
            }
        }
    }

    public static void downloadFile(int fileId) {

    }

    public static List<List<FileBean>> getFileList(int dormitoryId) throws IOException, JSONException {
        URL url = new URL(StaticVariable.GETFILELIST_SERVLET);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        OutputStream out = conn.getOutputStream();

        out.write((dormitoryId+"").getBytes());
        out.flush();
        out.close();
        conn.connect();
        //Log.e("tag", conn.getResponseCode()+"");
        if(conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            StringBuffer data0 = new StringBuffer();
            String buffer;
            while (((buffer) = bf.readLine()) != null) {
                data0.append(buffer);
            }
            JSONArray repJson = new JSONArray(data0.toString());
            List<List<FileBean>> list = new ArrayList<>();
            List<FileBean> fList;
            int l = repJson.length();
            JSONArray childJson;
            JSONObject json;
            FileBean fileBean;
            for(int i=0;i<l;i++) {
                childJson = repJson.getJSONArray(i);
                int ll = childJson.length();
                fList = new ArrayList<>();
                for(int j=0;j<ll;j++) {
                    json = childJson.getJSONObject(j);
                    fileBean = new FileBean();
                    fileBean.setId(json.getInt("id"));
                    fileBean.setDormitory(json.getString("dormitory"));
                    fileBean.setFileName(json.getString("fileName"));
                    fileBean.setIsSharing(json.getBoolean("isSharing"));
                    fileBean.setPath(json.getString("path"));
                    fileBean.setUserName(json.getString("userName"));
                    fileBean.setDormitoryId(json.getInt("dormitoryId"));
                    fList.add(fileBean);
                }
                list.add(fList);
            }
            return list;
        }
        return null;
    }
}
